import { ref } from 'vue'
import { defineStore } from 'pinia'
import { authApi } from '../api/index'

export const useAuthStore = defineStore('auth', () => {
  const isLoggedIn = ref(false)
  const user = ref(null)
  const token = ref(null)

  async function login(email, password) {
    try {
      const response = await authApi.login({ email, password })
      
      // 根据新的API响应格式处理登录结果
      if (response.code === 200 && response.data) {
        // 登录成功，保存用户信息
        const userData = response.data
        token.value = `admin_${userData.id}` // 生成一个临时token
        user.value = userData // 直接保存登录接口返回的用户数据
        isLoggedIn.value = true
        
        // 将用户信息存储到localStorage
        localStorage.setItem('user-info', JSON.stringify(userData))
        
        return {
          success: true,
          message: response.message || '登录成功'
        }
      } else {
        // 登录失败
        return {
          success: false,
          message: response.message || '登录失败'
        }
      }
    } catch (error) {
      console.error('登录失败:', error)
      return {
        success: false,
        message: '登录失败，请检查网络连接'
      }
    }
  }

  async function getUserInfo() {
    try {
      const response = await authApi.getUserInfo()
      if (response.code === 200 && response.data) {
        user.value = response.data
        return {
          success: true,
          data: response.data
        }
      } else {
        return {
          success: false,
          message: response.message || '获取用户信息失败'
        }
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return {
        success: false,
        message: '获取用户信息失败，请检查网络连接'
      }
    }
  }

  async function logout() {
    try {
      // 调用登出API
      await authApi.logout()
    } catch (error) {
      console.warn('登出API调用失败:', error)
    } finally {
      // 无论API调用是否成功，都清除本地状态
      user.value = null
      isLoggedIn.value = false
      token.value = null
    }
  }

  return {
    isLoggedIn,
    user,
    token,
    login,
    logout,
    getUserInfo
  }
}, {
  persist: [
    {
      key: 'auth-store',
      storage: localStorage,
      paths: ['isLoggedIn', 'user']
    },
    {
      key: 'auth-token',
      storage: localStorage,
      paths: ['token']
    }
  ]
})